package movieGandalf.DB;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.SQLException;
import java.util.HashSet;
import java.util.Iterator;
import java.util.Set;

public class MPAARatingsReader implements DataReader{
	
	public int read(Connection conn, InputStream in){
		String line = null;
		Set<String> mpaaRatings = new HashSet<String>();
		
		try {
			while ((line = MovieTools.getLine(in)) != null){
				
				int len = line.length();
				
				if (len<10 || !line.substring(0,10).equals("RE: Rated "))
					continue;
				
				int i = 0;
				for (i = 10;i<len;i++){
					if (line.charAt(i)==' '){
						break;
					}
				}
				
				if (i==10)
					continue;
				
				mpaaRatings.add(line.substring(10, i));
			}
			

			PreparedStatement stmt = conn.prepareStatement(new String("REPLACE INTO MPAARatings (mpaaRating) VALUES (?)"));
			
			Iterator<String> iter = mpaaRatings.iterator();
			String rating = null;
			
			while (iter.hasNext()){
				rating = iter.next();
				stmt.setString(1, rating);
				stmt.addBatch();
			}
			stmt.executeBatch();
			conn.commit();
			
			stmt.close();
		}
		
		catch (SQLException e) {
			e.printStackTrace();
			return 0;
		}
		catch (Exception e){
			e.printStackTrace();
		}
		finally {
			try{
				in.close();
			}
			catch(Exception e){
				return 0;
			}
		}
		
		return 1;
	}
	
}
